package com.baoming.kindeditor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.json.simple.JSONObject;
  
@SuppressWarnings("serial")
public class KindEditorServlet extends HttpServlet {
 
	@SuppressWarnings("unchecked")
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  
		String savePath = request.getSession().getServletContext().getRealPath(
				"/")
				+ "upload/";
		  
		String saveUrl = request.getContextPath() + "/upload/";
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		extMap.put("flash", "swf,flv");
		extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
		extMap.put("file", "gif,jpg,jpeg,png,bmp");  
									 											 
		long maxSize = 102400;
		response.setContentType("text/html; charset=UTF-8");
		if (!ServletFileUpload.isMultipartContent(request)) {
			response.getWriter().println(getError("不是文件类型"));
			return;
		}
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			response.getWriter().println(getError("不是有效文件 "));
			return;
		}
		if (!uploadDir.canWrite()) {
			response.getWriter().println(getError("目录不可写入"));
			return;
		}
		String dirName = request.getParameter("dir");
		// image
		if (dirName == null) {
			dirName = "image";
		}
		if (!extMap.containsKey(dirName)) {
			response.getWriter().println(getError("Ŀ¼����ȷ��"));
			return;
		}
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/"; 
		saveUrl += ymd + "/"; 
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		if (!dirFile.isDirectory()) {
			response.getWriter().println(getError("不是有效的保存路径"));
			return;
		} 
		
		if (!dirFile.canWrite()) {
			response.getWriter().println(getError("文件不可写入"));
			return;
		}
		MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
		String fileName = wrapper.getFileNames("imgFile")[0];
 
		File file = wrapper.getFiles("imgFile")[0];
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1)
				.toLowerCase();
		if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(
				fileExt)) {
			response.getWriter().println(getError("不是可上传的文件类型"
					+ extMap.get(dirName) + " "));
			return;
		}
		if (file.length() > maxSize) {
			response.getWriter().println(getError("文件太大了"));
			return;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String newImgName = df.format(new Date()) + "_"
				+ new Random().nextInt(1000) + "." + fileExt;
		byte[] buffer = new byte[1024];
		FileOutputStream fos = new FileOutputStream(savePath + "/" + newImgName);
		InputStream in = new FileInputStream(file);
		try {
			int num = 0;
			while ((num = in.read(buffer)) > 0) {
				fos.write(buffer, 0, num);
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
		} finally {
			in.close();
			fos.close();
		}
		 
        JSONObject obj = new JSONObject();  
        obj.put("error", 0);  
        obj.put("url", saveUrl +"/" + newImgName);   
        response.getWriter().println(obj.toJSONString()); 
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
